from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from taunt.ViewSerializers import SpitsModelSerializer
from users.models import Spit


class SpitsModelViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitsModelSerializer

    def list(self, request, *args, **kwargs):
        spit = self.queryset.filter(parent=None).order_by("-publishtime")
        conn = get_redis_connection('collection')
        new_list = []
        if not request.user.is_anonymous:
            for x in spit:
                collect = conn.hget('collect_' + str(request.user.id), x.id)
                if collect:
                    x.collected = True
                else:
                    x.collected = False
                updatethumbup = conn.hget('updatethumbup_' + str(request.user.id), x.id)
                if updatethumbup:
                    x.hasthumbup = True
                else:
                    x.hasthumbup = False
                new_list.append(x)
            p = self.serializer_class(new_list,many=True)
            return Response(p.data)
        else:
            for x in spit:
                x.collected = False
                x.hasthumbup = False
                new_list.append(x)
            p = self.serializer_class(new_list, many=True)
            return Response(p.data)

    def create(self, request, *args, **kwargs):
        dict = request.data
        if not request.user.is_anonymous:
            # 当用户存在时
            dict['userid'] = request.user.id
            dict['nickname'] = request.user.username
            p = self.serializer_class(data=dict)
            p.is_valid(raise_exception=True)
            p.save()
            return Response({'success': True})

        else:
            # 当用户不存在时
            dict['userid'] = 'anonymous'
            p = self.serializer_class(data=dict)
            p.is_valid(raise_exception=True)
            p.save()
            return Response({'success': True})

    @action(methods=['put'], detail=True)
    def collect(self,request,pk):
        if not request.user.is_anonymous:
            data = self.get_object()
            conn = get_redis_connection('like')
            collect = conn.hget('collect_' + str(request.user.id), str(data.id))
            if not collect:
                conn.hset('collect_' + str(request.user.id), str(data.id), 'True')
                data.collected = True
                data.save()
            else:
                data.collected = False
                conn.hdel('collect_' + str(request.user.id), str(data.id))
                data.save()
            return Response({'success': True, 'message': 'OK'})
        else:
            return Response({'success': False, 'message': '未登录'})

    @action(methods=['put'], detail=True)
    def updatethumbup(self, request, pk):
        if not request.user.is_anonymous:
            data = self.get_object()
            conn = get_redis_connection('like')
            updatethumbup = conn.hget('updatethumbup_' + str(request.user.id), str(data.id))
            if not updatethumbup:
                conn.hset('updatethumbup_' + str(request.user.id), str(data.id), 'True')
                data.hasthumbup = True
                data.thumbup += 1
                data.save()
            else:
                data.hasthumbup = False
                data.thumbup -= 1
                data.save()
                conn.hdel('updatethumbup_' + str(request.user.id), str(data.id))
            return Response({'success': True, 'message': 'OK'})
        else:
            return Response({'success': False, 'message': '未登录'})

    @action(methods=['get'], detail=True)
    def children(self,request,pk):
        data = self.queryset.filter(parent=pk)
        p = self.serializer_class(data, many=True)
        return Response(p.data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.visits += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
